package com.miku.blog.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shkstart
 * @create ${}YEAR-06-02 7:29
 */
public class UserAgentParseUtils {

    public static UserAgentParse parseUserAgent(@Nullable String userAgentString) {
        if (!StringUtils.hasText(userAgentString)) {
            HttpServletRequest request = HttpUtils.getHttpServletRequest();
            userAgentString = request.getHeader("User-Agent");
        }
        UserAgent userAgent = new UserAgent(userAgentString);
        Browser browser = userAgent.getBrowser();
        String browserName = browser.getName();
        //Edge使用的是谷歌内核 , 此处是为了判断 实际浏览器是 Edge 还是 Chrome
        if (browserName.startsWith("Chrome")) {
            //若User-Agent中包含Edg, 则说明是Edge浏览器
            int indexOf = userAgentString.indexOf("Edg");
            if (indexOf != -1) {
                String var1 = userAgentString.substring(indexOf);
                var1 = var1.indexOf(" ") == -1 ? var1 : var1.substring(var1.indexOf(" "));
                String name = var1.substring(0, var1.indexOf("/"));
                String version = var1.substring(var1.indexOf("/") + 1);
                name = "Edg".equals(name) ? name + "e" : name;
                version = version.substring(0, 2);//获取版本号前两位
                browserName = new StringBuilder().append(name)
                        .append(" ")
                        .append(version)
                        .toString();
            }
        }
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        String systemName = operatingSystem.getName();
        return new UserAgentParse(browserName,systemName);
    }


    @Data
    @AllArgsConstructor
    public static class UserAgentParse {
        private String browserName;
        private String systemName;
    }

}
